﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using NPOI.Util;
using Simple.Repository.Models.DeviceManagement;
using Simple.Repository.Models.MorningCheck;
using Simple.Services.MQTT.Model;
using Simple.Services.System.DeviceManagement.Models;
using Simple.Services.System.MorningCheck.Models;
using Simple.Services.System.Recipes.Models;
using static Simple.Services.System.MorningCheck.Models.DeviceModel;

namespace Simple.Services.System.DeviceManagement
{
    public class DeviceService : BusinessBaseService
    {
        private readonly SimpleDbContext _context;

        public DeviceService(SimpleDbContext context,
            ISimpleService services) : base(services)
        {
            _context = context;
        }

        /// <summary>
        /// 添加设备
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<int> AddAsync(DeviceCreateOrUpdateModel model)
        {
            if (model.ClassesId.HasValue)
            {
                var calssInfo = await _context.Set<SysClasses>().FirstOrDefaultAsync(m => m.Id == model.ClassesId);
                if (calssInfo == null)
                {
                    throw AppResultException.Status409Conflict("班级不存在！");
                }

                var cInfo = await _context.Set<Device>().FirstOrDefaultAsync(m => m.ClassesId == model.ClassesId.Value);
                if (cInfo != null)
                {
                    throw AppResultException.Status409Conflict("该班级已绑定设备啦！");
                }
            }


            var record = MapperHelper.Map<Device>(model);
            record.DeviceType = model.EnumDeviceType;
            if (model.ApplicablePopulation != null && model.ApplicablePopulation.Count > 0)
            {
                record.ApplicablePopulation = string.Join(",", model.ApplicablePopulation);
            }

            await _context.AddAsync(record);
            return await _context.SaveChangesAsync();
        }

        /// <summary>
        /// 修改设备
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<int> UpdateAsync(DeviceCreateOrUpdateModel model)
        {
            if (!model.Id.HasValue)
            {
                throw AppResultException.Status409Conflict("参数错误,设备Id参数不能为Null!");
            }
            var info = await _context.Set<Device>()
                .FirstOrDefaultAsync(m => model.Id == m.Id);

            if (info == null)
            {
                throw AppResultException.Status409Conflict("设备不存在！");
            }

            info.IpAddress = model.IpAddress;
            info.ClassesId = model.ClassesId;
            info.Name = model.Name;
            info.Number = model.Number;
            info.DeviceType = model.EnumDeviceType;
            info.DeviceKey = model.DeviceKey;
            info.DeviceSecret = model.DeviceSecret;
            info.IsFace = model.IsFace;
            info.IsCard = model.IsCard;

            if (model.ApplicablePopulation != null && model.ApplicablePopulation.Count > 0)
            {
                info.ApplicablePopulation = string.Join(",", model.ApplicablePopulation);
            }

            _context.Update(info);
            int ret = await _context.SaveChangesAsync();

            if (ret == 0)
            {
                throw AppResultException.Status200OK("更新记录数为0");
            }

            return ret;
        }

        /// <summary>
        /// 删除设备
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<int> DeleteAsync(Guid id)
        {
            var info = await _context.Set<Device>().FirstOrDefaultAsync(s => s.Id == id);
            if (info != null)
            {
                _context.RemoveRange(info);
                return await _context.SaveChangesAsync();
            }
            return 0;
        }

        public async Task<List<SyncDataViewModel>> GetSyncDataList()
        {
            var result = new List<SyncDataViewModel>();
            var query = await OrganizationFilter(_context.Set<Device>());

            var positions = await query.Where(x => x.DeviceType != (int)EnumDeviceType.sound).ToListAsync();
            foreach (var item in positions)
            {
                var d = new SyncDataViewModel();
                d.Id = item.Id;
                d.DeviceType = item.DeviceType;
                d.DeviceKey = item.DeviceKey;
                d.Name = item.Name;
                if (!string.IsNullOrEmpty(item.ApplicablePopulation))
                {
                    d.ApplicablePopulation = item.ApplicablePopulation.Split(',').Select(x => int.Parse(x)).ToList();
                }
                result.Add(d);
            }
            return result;
        }

        /// <summary>
        /// 设备分页列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageResultModel<DeviceModel>> GetPageAsync(DevicePageQueryModel input)
        {
            var result = new PageResultModel<DeviceModel>();

            var returnLists = new List<DeviceModel>();

            //所有班级信息
            var classInfos = await OrganizationFilter(_context.Set<SysClasses>().AsQueryable());
            var classLists = await classInfos.ToListAsync();

            var query = await OrganizationFilter(_context.Set<Device>());


            //组装数据
            var device = await query.ToListAsync();
            bool isRecords = false;
            if (device != null && device.Count > 0)
            {
                foreach (var c in device)
                {
                    string className = "";
                    if (c.ClassesId.HasValue)
                    {
                        className = classLists.FirstOrDefault(x => x.Id == c.ClassesId.Value).Name;
                    }

                    DeviceModel model = new DeviceModel
                    {
                        Id = c.Id,
                        ClassesId = c.ClassesId,
                        ClassesName = className,
                        IpAddress = c.IpAddress,
                        Name = c.Name,
                        Number = c.Number,
                        DeviceKey = c.DeviceKey,
                        DeviceSecret = c.DeviceSecret,
                        DeviceType = c.DeviceType,
                        ApplicablePopulation = !string.IsNullOrEmpty(c.ApplicablePopulation) ? c.ApplicablePopulation.Split(',').Select(x => int.Parse(x)).ToList() : new List<int>(),
                        IsCard = c.IsCard,
                        IsFace = c.IsFace,
                    };

                    returnLists.Add(model);
                }

                if (returnLists != null && returnLists.Count > 0)
                {
                    // 获取总数量
                    result.TotalRows = returnLists.Count;
                    // 分页查询
                    result.Rows = returnLists.Skip((input.PageNo - 1) * input.PageSize).Take(input.PageSize).ToList();
                    result.SetPage(input);
                    result.CountTotalPage();
                }
            }

            return result;
        }

    }
}
